import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    accessToken: localStorage.getItem('access_token') || '',
    user: JSON.parse(localStorage.getItem('user') || 'null'),
  }),
  getters: {
    isAuthenticated: (s) => !!s.accessToken,
  },
  actions: {
    setAuth(accessToken, user) {
      this.accessToken = accessToken
      this.user = user || null
      localStorage.setItem('access_token', accessToken || '')
      if (user) localStorage.setItem('user', JSON.stringify(user))
    },
    clearAuth() {
      this.accessToken = ''
      this.user = null
      localStorage.removeItem('access_token')
      localStorage.removeItem('user')
    }
  }
})